package com.chen.lock;

import java.util.concurrent.locks.ReentrantLock;

// lock锁
public class SaleTicketDemo02 {
    public static void main(String[] args) {

        Ticket2 ticket = new Ticket2();

        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sales(); }, "A").start();
        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sales(); }, "B").start();
        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sales(); }, "C").start();

    }
}

// 资源类
class Ticket2 {
    private int number = 30;

    ReentrantLock lock = new ReentrantLock();// new一个锁

    public void sales() {

        lock.lock();// 加锁

        try {
            // 业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了一张票， 剩余：" + number--);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 释放锁，放入finally代码块中
        }

    }
}
